// DOM元素
const startBtn = document.getElementById('startBtn');
const stopBtn = document.getElementById('stopBtn');
const transcript = document.getElementById('transcript');
const statusEl = document.getElementById('status');
const languageSelect = document.getElementById('language');
const recordingIndicator = document.getElementById('recordingIndicator');
const copyBtn = document.getElementById('copyBtn');
const downloadBtn = document.getElementById('downloadBtn');
const clearBtn = document.getElementById('clearBtn');
const notification = document.getElementById('notification');
const notificationMessage = document.getElementById('notificationMessage');

// 标签页相关元素
const micTab = document.getElementById('micTab');
const fileTab = document.getElementById('fileTab');
const micSection = document.getElementById('micSection');
const fileSection = document.getElementById('fileSection');

// 文件上传相关元素
const dropArea = document.getElementById('dropArea');
const audioFileInput = document.getElementById('audioFileInput');
const fileInfo = document.getElementById('fileInfo');
const fileName = document.getElementById('fileName');
const fileSize = document.getElementById('fileSize');
const clearFileBtn = document.getElementById('clearFileBtn');
const audioPlayer = document.getElementById('audioPlayer');
const transcribeBtn = document.getElementById('transcribeBtn');
const fileStatus = document.getElementById('fileStatus');

// 语音识别变量
let recognition;
let isRecording = false;
let finalTranscript = '';
let interimTranscript = '';
let audioFile = null;
let isProcessingFile = false;

// 检查浏览器兼容性
const SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition;

// 初始化函数
function init() {
    if (!SpeechRecognition) {
        showStatus('您的浏览器不支持语音识别功能，请使用Chrome、Edge或Safari浏览器。', true);
        startBtn.disabled = true;
        return;
    }

    // 设置事件监听器 - 实时录音
    startBtn.addEventListener('click', startRecording);
    stopBtn.addEventListener('click', stopRecording);
    copyBtn.addEventListener('click', copyText);
    downloadBtn.addEventListener('click', downloadText);
    clearBtn.addEventListener('click', clearText);
    languageSelect.addEventListener('change', updateLanguage);

    // 设置事件监听器 - 标签页切换
    micTab.addEventListener('click', () => switchTab('mic'));
    fileTab.addEventListener('click', () => switchTab('file'));

    // 设置事件监听器 - 文件上传
    audioFileInput.addEventListener('change', handleFileSelect);
    clearFileBtn.addEventListener('click', clearFile);
    transcribeBtn.addEventListener('click', transcribeFile);

    // 拖放功能
    ['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => {
        dropArea.addEventListener(eventName, preventDefaults, false);
    });

    ['dragenter', 'dragover'].forEach(eventName => {
        dropArea.addEventListener(eventName, highlight, false);
    });

    ['dragleave', 'drop'].forEach(eventName => {
        dropArea.addEventListener(eventName, unhighlight, false);
    });

    dropArea.addEventListener('drop', handleDrop, false);
}

// 开始录音
function startRecording() {
    if (isRecording) return;

    // 创建语音识别实例
    recognition = new SpeechRecognition();
    recognition.continuous = true;
    recognition.interimResults = true;
    recognition.lang = languageSelect.value;

    // 语音识别事件
    recognition.onstart = () => {
        isRecording = true;
        updateUI(true);
    };

    recognition.onresult = (event) => {
        interimTranscript = '';
        
        for (let i = event.resultIndex; i < event.results.length; i++) {
            if (event.results[i].isFinal) {
                finalTranscript += event.results[i][0].transcript;
            } else {
                interimTranscript += event.results[i][0].transcript;
            }
        }

        updateTranscript();
    };

    recognition.onerror = (event) => {
        console.error('语音识别错误:', event.error);
        showStatus(`错误: ${getErrorMessage(event.error)}`, true);
        
        if (event.error === 'not-allowed') {
            showNotification('请允许麦克风访问权限以使用此功能');
            stopRecording();
        }
    };

    recognition.onend = () => {
        if (isRecording) {
            // 如果还在录音状态，重新启动识别（处理自动停止的情况）
            recognition.start();
        }
    };

    // 开始识别
    try {
        recognition.start();
        showStatus('正在录音...');
    } catch (error) {
        console.error('启动语音识别失败:', error);
        showStatus('启动语音识别失败，请刷新页面重试', true);
    }
}

// 停止录音
function stopRecording() {
    if (!isRecording) return;
    
    isRecording = false;
    
    if (recognition) {
        recognition.stop();
    }
    
    updateUI(false);
    
    // 将临时结果也添加到最终结果中
    if (interimTranscript) {
        finalTranscript += interimTranscript;
        interimTranscript = '';
        updateTranscript();
    }
    
    showStatus('录音已停止');
}

// 更新界面
function updateUI(recording) {
    startBtn.disabled = recording;
    stopBtn.disabled = !recording;
    
    if (recording) {
        recordingIndicator.classList.add('active');
    } else {
        recordingIndicator.classList.remove('active');
    }
}

// 更新转录内容
function updateTranscript() {
    transcript.innerHTML = finalTranscript + 
        '<span style="color: gray;">' + interimTranscript + '</span>';
    
    // 自动滚动到底部
    transcript.scrollTop = transcript.scrollHeight;
}

// 显示状态
function showStatus(message, isError = false) {
    statusEl.textContent = message;
    statusEl.style.color = isError ? '#ff4a4a' : '#555';
}

// 显示文件状态
function showFileStatus(message, isError = false) {
    fileStatus.textContent = message;
    fileStatus.style.color = isError ? '#ff4a4a' : '#555';
}

// 复制文本
function copyText() {
    if (!finalTranscript.trim()) {
        showNotification('没有可复制的文本');
        return;
    }
    
    navigator.clipboard.writeText(finalTranscript)
        .then(() => {
            showNotification('文本已复制到剪贴板');
        })
        .catch(err => {
            console.error('复制失败:', err);
            showNotification('复制失败，请手动选择并复制');
        });
}

// 下载文本
function downloadText() {
    if (!finalTranscript.trim()) {
        showNotification('没有可下载的文本');
        return;
    }
    
    const blob = new Blob([finalTranscript], { type: 'text/plain' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    
    // 创建文件名（当前日期时间）
    const date = new Date();
    const fileName = `语音转文本_${date.getFullYear()}${padZero(date.getMonth() + 1)}${padZero(date.getDate())}_${padZero(date.getHours())}${padZero(date.getMinutes())}.txt`;
    
    a.href = url;
    a.download = fileName;
    a.click();
    
    URL.revokeObjectURL(url);
    showNotification(`文本已下载为 ${fileName}`);
}

// 清除文本
function clearText() {
    if (!finalTranscript.trim() && !interimTranscript.trim()) {
        showNotification('没有可清除的文本');
        return;
    }
    
    finalTranscript = '';
    interimTranscript = '';
    updateTranscript();
    showNotification('文本已清除');
}

// 更新语言
function updateLanguage() {
    if (isRecording) {
        stopRecording();
        setTimeout(startRecording, 300);
    }
    
    showStatus(`语言已切换到: ${languageSelect.options[languageSelect.selectedIndex].text}`);
}

// 切换标签页
function switchTab(tab) {
    // 停止任何进行中的录音
    if (isRecording) {
        stopRecording();
    }

    // 更新标签页样式
    if (tab === 'mic') {
        micTab.classList.add('active');
        fileTab.classList.remove('active');
        micSection.classList.add('active');
        fileSection.classList.remove('active');
    } else {
        fileTab.classList.add('active');
        micTab.classList.remove('active');
        fileSection.classList.add('active');
        micSection.classList.remove('active');
    }
}

// 处理文件选择
function handleFileSelect(event) {
    const files = event.target.files;
    if (files.length > 0) {
        handleFile(files[0]);
    }
}

// 处理拖放文件
function handleDrop(event) {
    const dt = event.dataTransfer;
    const files = dt.files;
    
    if (files.length > 0) {
        handleFile(files[0]);
    }
}

// 处理文件
function handleFile(file) {
    // 检查是否为音频文件
    if (!file.type.startsWith('audio/')) {
        showFileStatus('请上传音频文件', true);
        showNotification('只支持音频文件格式');
        return;
    }

    audioFile = file;
    
    // 更新文件信息
    fileName.textContent = file.name;
    fileSize.textContent = formatFileSize(file.size);
    
    // 更新界面
    dropArea.style.display = 'none';
    fileInfo.classList.remove('hidden');
    
    // 设置音频播放器
    const url = URL.createObjectURL(file);
    audioPlayer.src = url;
    
    // 启用转写按钮
    transcribeBtn.disabled = false;
    
    showFileStatus('文件已就绪，点击"开始转写"按钮进行识别');
}

// 清除文件
function clearFile() {
    audioFile = null;
    audioPlayer.src = '';
    audioFileInput.value = '';
    
    // 重置界面
    dropArea.style.display = 'block';
    fileInfo.classList.add('hidden');
    
    // 如果正在处理文件，停止处理
    if (isProcessingFile) {
        if (recognition) {
            recognition.stop();
        }
        isProcessingFile = false;
    }
    
    showFileStatus('');
}

// 转写文件
async function transcribeFile() {
    if (!audioFile || isProcessingFile) return;
    
    isProcessingFile = true;
    transcribeBtn.disabled = true;
    showFileStatus('正在处理音频文件，请稍候...');
    
    try {
        // 存储当前转录内容，避免与实时转录混合
        const prevFinalTranscript = finalTranscript;
        finalTranscript = '';
        interimTranscript = '';
        updateTranscript();

        // 创建语音识别实例
        if (SpeechRecognition) {
            recognition = new SpeechRecognition();
            recognition.continuous = true;
            recognition.interimResults = true;
            recognition.lang = languageSelect.value;
            
            recognition.onresult = (event) => {
                interimTranscript = '';
                
                for (let i = event.resultIndex; i < event.results.length; i++) {
                    if (event.results[i].isFinal) {
                        finalTranscript += event.results[i][0].transcript;
                    } else {
                        interimTranscript += event.results[i][0].transcript;
                    }
                }
                
                updateTranscript();
            };
            
            recognition.onerror = (event) => {
                console.error('文件转写错误:', event.error);
                showFileStatus(`错误: ${getErrorMessage(event.error)}`, true);
                isProcessingFile = false;
                transcribeBtn.disabled = false;
            };
            
            recognition.onend = () => {
                // 将最后的临时结果添加到最终结果
                if (interimTranscript) {
                    finalTranscript += interimTranscript;
                    interimTranscript = '';
                    updateTranscript();
                }
                
                showFileStatus('音频文件处理完成');
                isProcessingFile = false;
                transcribeBtn.disabled = false;
            };
            
            // 开始识别
            recognition.start();
            
            // 播放音频文件
            audioPlayer.play();
            
            // 监听音频播放结束事件
            audioPlayer.onended = () => {
                setTimeout(() => {
                    if (recognition) {
                        recognition.stop();
                    }
                }, 1000); // 给识别一些额外时间处理最后的音频
            };
        } else {
            // 浏览器不支持语音识别
            showFileStatus('您的浏览器不支持音频文件转写功能', true);
            isProcessingFile = false;
            transcribeBtn.disabled = false;
            
            // 恢复之前的转录内容
            finalTranscript = prevFinalTranscript;
            updateTranscript();
        }
    } catch (error) {
        console.error('音频文件处理失败:', error);
        showFileStatus('音频文件处理失败', true);
        isProcessingFile = false;
        transcribeBtn.disabled = false;
    }
}

// 显示通知
function showNotification(message) {
    notificationMessage.textContent = message;
    notification.classList.add('show');
    
    setTimeout(() => {
        notification.classList.remove('show');
    }, 3000);
}

// 获取错误消息
function getErrorMessage(error) {
    const errorMessages = {
        'no-speech': '没有检测到语音',
        'audio-capture': '无法捕获音频',
        'not-allowed': '麦克风访问被拒绝',
        'network': '网络错误',
        'aborted': '语音识别被中止',
        'service-not-allowed': '服务不可用',
        'bad-grammar': '语法错误',
        'language-not-supported': '不支持选择的语言'
    };
    
    return errorMessages[error] || '未知错误';
}

// 格式化文件大小
function formatFileSize(bytes) {
    if (bytes === 0) return '0 Bytes';
    
    const k = 1024;
    const sizes = ['Bytes', 'KB', 'MB', 'GB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
}

// 防止默认拖放行为
function preventDefaults(e) {
    e.preventDefault();
    e.stopPropagation();
}

// 高亮拖放区域
function highlight() {
    dropArea.classList.add('dragover');
}

// 取消高亮拖放区域
function unhighlight() {
    dropArea.classList.remove('dragover');
}

// 辅助函数：填充前导零
function padZero(num) {
    return String(num).padStart(2, '0');
}

// 页面加载时初始化
document.addEventListener('DOMContentLoaded', init); 